const app = getApp()
const { upTime } = require('/util/public')
Page({
  data: {
    couponlist:[],
    pagenum:'',
    choose:false,
    shopid: '',
couponstype:{
  1: '通用券', 2: '产品券', 3: '专属劵', 4: '购买券', 5: '奖品券', 6: '账单券',7:'抢购券'
},
    couponstatus:undefined,
    types: [
      { title: '全部', state: '', order: [], totalCount: null, page: 1 },
      { title: '待使用', state:0, order: [], totalCount: null, page: 1 },
      { title: '已使用', state: 1, order: [], totalCount: null, page: 1 },
      { title: '已过期', state:2, order: [], totalCount: null, page: 1 },


    ],
    nowtimes:'',
    activeTab: 0,
    status: ['', "待付款", "待审核", "待发货", "待收货", "待归还", "归还中", "交易完成", "完结订单", "订单关闭（用户）", "订单关闭（系统）", "订单关闭（商家）", "已完成", '即将到期', '申请取消'],

    totalPage: null,
  },
  onLoad(query) {
    // this.coupons()
    console.log("订单列表页面", query)
    if (query.ids) {
      this.setData({
        shopid: query.ids,
        pagenum: query.page
      })
    }
    if (query.param){
      this.setData({
        choose:true
      })
    }else{
      this.setData({
        choose: false
      })
    }
    // if (query.param) {
    //   let index = JSON.parse(query.param)
    //   this.handleTabClick({ index: index, tabsName: 'activeTab' })
    // } else {
    //   let index = 0;
    //   this.handleTabClick({ index: index, tabsName: 'activeTab' })
    // };
    // app._init_(this);

    // //console.log("11111111111")
    // my.request({
    //   url: 'https://api.jxqyfw.com/api/pd/getOne?t=1643001052517&com=sf&no=SF1148913926689&receiverPhone=0681',
    //   success: (result) => {
    //     //console.log(result)
    //   },
    //   fail: () => {

    //   },
    //   complete: () => {

    //   }
    // });


  },
  onShow(){
    let timestamp = new Date().getTime()
    console.log("222", timestamp)
    var times = upTime("%Y-%M-%D %h:%m:%s", timestamp)
    console.log("7777777777", times)
    this.setData({
      nowtimes: times
    })
    this.couponuserlist()
  },
  gopay(e){
    console.log("111111111111111*****", getCurrentPages())
   

   
    if (this.data.choose){
       if (e.target.dataset.type == '7' || e.target.dataset.type == '5') {
         my.navigateTo({

           url: `/pages/product/detail/detail?param=${encodeURIComponent(JSON.stringify(e.target.dataset.productid))}`
         })
       } else {
      my.switchTab({
        url: '/pages/main/home/home'
      })
    }
    }else{
      var pages = getCurrentPages();

      var prevPage = pages[pages.length - 2]; //上一个页面
      console.log("222222222====", pages, prevPage)
      prevPage.setData({
        yhjid: e.target.dataset.id,
        choosemoney: e.target.dataset.money
      })
      my.navigateBack();
  
 }
  },
  couponuserlist(){
    const types = this.data.types;


    let e= {}
      e.status = types[this.data.activeTab].state,
    e.page =false
    app.order.couponuserlist(e)
      .then(res => {
      console.log("哟挥拳rs", res)
  if(res.code == '0'){
    res.data.forEach((json) => {
      //   console.log("一元首月1", json)
      json.couponJson = JSON.parse(json.couponJson)

    })

    if (this.data.shopid != '') {
      let arr = res.data.filter(item => {
        console.log("111`````", this.data.shopid, item.productId)
        return (item.productId == this.data.shopid || item.productId == 0)

      })
      console.log("1111", arr)
      this.setData({
        couponlist: arr
      })
    } else {
      this.setData({
        couponlist: res.data
      })

    }
    console.log("哟挥拳r11111s", this.data.couponlist)
  }

        // dddddthis.handleChange(4)
      })
  },
  // tabs
  handleTabClick({ index = 0, tabsName }) {
    console.log("11111", index, tabsName)
    this.setData({
      [tabsName]: index,
    });
    const types = this.data.types;
    if (types[index].totalCount == null) {
      this.couponuserlist()
    }
  },
 coupons(){
   app.other.couponUser()
     .then(res => {
       //console.log("youhuiquan", res)


       // dddddthis.handleChange(4)
     })
 },
  // 获取数据
  get_meg() {
    this.setData({ show: true });
    const types = this.data.types;
    let data = {
      status: types[this.data.activeTab].state,
      pageNo: types[this.data.activeTab].page,
      pageSize: 10,
    }
    app.order.page(data)
      .then(res => {
        //console.log(res)
        res.data.data.forEach((item) => {

          item.paramsOld = item.params;
          item.params = JSON.parse(item.params);
          item.createtime = upTime("%Y-%M-%D %h:%m:%h", item.createtime);
          item.starttime = item.starttime ? upTime("%Y-%M-%D", item.starttime) : '';
          item.endtime = item.endtime ? upTime("%Y-%M-%D", item.endtime) : '';
          if (item.status == 4 && item.productOrderShipment != null) {
            item.flowOne = {
              id: item.id,
              receiverPhone: item.phone.slice(-4, item.phone.length),
              com: item.productOrderShipment.company,
              no: item.productOrderShipment.number,
            }
          } else if (item.status == 6 && item.productOrderRecycle != null) {
            item.flowOne = {
              id: item.id,
              receiverPhone: item.shopsVo.phone.slice(-4, item.phone.length),
              com: item.productOrderRecycle.company,
              no: item.productOrderRecycle.number,
            }
          }
          else {
            item.flowOne = null
          }
        })
        types[this.data.activeTab].order = [...types[this.data.activeTab].order, ...res.data.data]
        types[this.data.activeTab].totalCount = res.data.totalCount
        this.setData({ types })
        setTimeout(() => {
          this.setData({ show: false });
        }, 200)
      })
  },

  // btn 订单按钮
  //   联系商家
  makePhoneCall(e) {
    // //console.log(e.target.dataset.phone)
    let phone = e.target.dataset.phone;
    my.makePhoneCall({ number: phone });
  },
  // 关闭订单
  onCancel(e) {
    // //console.log(e.target.dataset.item)
    let id = e.target.dataset.item.id;
    let status = e.target.dataset.item.status;
    my.prompt({
      title: '申请取消',
      message: '请输入取消原因，否则无法为你取消',
      placeholder: '请输入取消原因',
      okButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        //console.log(result)
        if (!result.ok) {
          return
        }
        if (result.inputValue) {
          if (status == 1) {
            app.order.canOrder(id, { cont: result.inputValue })
              .then((res) => {
                my.alert({
                  title: "取消成功",
                  success: () => {
                    this.resetOrder()
                  }
                });
              })
          } else if (status == 2) {
            app.order.canOrder(id, { cont: result.inputValue })
              .then((res) => {
                //console.log(res)
                my.alert({
                  title: "申请成功",
                  success: () => {
                    this.resetOrder()
                  }
                });

              })
          }
        } else {
          my.showToast({
            type: 'exception',
            content: '请输入取消原因',
          });
        }
      },
    });
  },
  // 撤销申请
  noCancel(e) {
    let cancelRequests = e.target.dataset.item.productOrderCancelRequests
    let id = cancelRequests[cancelRequests.length - 1].id
    my.confirm({
      title: '温馨提示',
      content: '是否撤回订单取消申请',
      confirmButtonText: '立即撤回',
      cancelButtonText: '暂不撤回',
      success: (result) => {
        if (result.confirm) {
          app.order.canOrder(id)
            .then(red => {
              if (res.code == 200) {
                my.alert({
                  title: "撤回成功",
                  success: () => {
                    this.resetOrder()
                  }

                });
              }
            })
        }
      },
    });
  },

  // 冻结
  onBuy(e) {
    let that = this
    const data = e.target.dataset.data;
    app.order.freeze(data.id)
      .then(pay => {
        my.tradePay({
          orderStr: pay.data, // 完整的支付参数拼接成的字符串，从服务端获取
          success: (res) => {
            //console.log(res)
            if (res.resultCode == 9000) {
              my.alert({
                content: "支付成功",
              });
              this.resetOrder()
            }
          },
          fail: (res) => {
            my.alert({
              content: res.memo,
            });
          }
        });
      })
  },
  // 支付
  onReplenish(e) {
    let that = this
    let oid = e.target.dataset.data.productOrderRecordVoList[0].oid
    let id = e.target.dataset.data.productOrderRecordVoList[0].id
    app.order.freeze(oid, id)
      .then(res => {
        my.tradePay({
          tradeNO: res.data,
          success: function (res) {
            // //console.log(res)
            if (res.resultCode == 9000) {
              my.alert({
                content: "支付成功",
              });
              this.resetOrder()
            } else {
              my.alert({
                content: res.memo,
              });
            }
          },

        });
      })
  },
  // 确认收货
  ConfirmReceipt(e) {
    let id = e.target.dataset.id
    app.order.receiving(id)
      .then(res => {
        if (res.code == 200) {
          my.alert({
            content: "提交成功",
            success: () => {
              this.resetOrder()
            }
          })
        } else {
          my.alert({
            content: res.msg
          })
        }
      })
  },
  // 跳转
  navigateTo(e) {
    app.navigateTo(e)
  },

  // 重置订单列表
  resetOrder() {
    const types = this.data.types;
    const tabIndex = this.data.activeTab;
    types[tabIndex].order = [];
    types[tabIndex].totalCount = null;
    this.setData({ types });
    this.onLoad({ param: this.data.activeTab });
  },

  // 下拉刷新
  onPullDownRefresh() {
    // this.resetOrder()
    setTimeout(() => {
      my.stopPullDownRefresh({
        complete(res) {
        }
      })
    }, 1000)
  },
  stopPullDownRefresh() {
    my.stopPullDownRefresh({
      complete(res) {
        // //console.log(res, new Date())
      }
    })
  },
  //   下拉加载
  onReachBottom() {
    const that = this
    const types = this.data.types;
    const tabIndex = this.data.activeTab
    try {
      // 判断是否还有数据需要加载
      if (types[tabIndex].order.length < types[tabIndex].totalCount) {
        types[tabIndex].page++
        that.get_meg();
      }
    } catch (e) { }
  },
});
